<?php
$this->useClass("Handler_Community");
class Action_Community_AjaxComMembers extends Handler_Community
{
	var $ajax_functions = array(
	'ajax_doChangeUserInfo',
	'ajax_doExorcizeUser',
	);

	private function returnErrorStatus($cp, $dataStatus = 'error') {
		$status = &$cp->add_node('status');
		$status->set_data(-1);
		$data = &$cp->add_node('data');
		$data->set_data($dataStatus);
		$this->shutdown();
	}

	private function getRoles() {
		$roles_ql = 'select objects where role.oid == 9 OR role.oid == 12'; // показываем только часть ролей #196
		$rs = $this->ctx->store->find($roles_ql);
		if ($rs) {
			$roles = array();
			while ($role = $rs->next()) {
				$t = $role->data;
				$t['oid'] = $role->id;
				$roles[$role->id] = $t;
			}
		}
		return $roles;
	}

	private function getCommunityUsers() {
		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
		$this->rh->UseClass("AggregatedModel_Feed_ReaderUsers");

		$model = new AggregatedModel_Feed_ReaderUsers();
		$model->rh = $this->rh;
		$model->setModelParams( 'community_oid', $this->aa->acl_data['comity_oid'] );
		$model->doStuff();
		return $model->getItems();
	}

	private function getModeratorOID( $roles ) {
		foreach ( $roles as $role ) {
			if ( 'moderator' == $role['name'] ) {
				return $role['oid'];
			}
		}

		return 0;
	}

	private function getUserRole( $users, $user_id, $roles ) {
		foreach ( $users as $user ) {
			if ( $user_id == $user['oid'] ) {
				return $roles[$user['role_oid']]['oid'];
			}
		}

		return 0;
	}

	private function getModeratorsCount($users, $moderator_oid) {
		$count = 0;
		foreach ( $users as $user ) {
			if( $moderator_oid == $user['role_oid'] ) {
				$count++;
			}
		}
		return $count;
	}

	public function ajax_doChangeUserInfo ( $user_id, $role_oid )
	{
		$cp = &$this->rh->ctx->cp;

		$operations = $this->aa->getAvailableOperations();
		if ( !$this->aa->is_granted( array( 'community_edit') ) ) {
			$status = &$cp->add_node('status');
			$status->set_data(-1);
			$data = &$cp->add_node('data');
			$data->set_data('access denied');
			$this->shutdown();
			return false;
		}
		$community_oid = $this->aa->acl_data['comity_oid'];

		$users = $this->getCommunityUsers();
		$roles = $this->getRoles();
		$moderator_oid = $this->getModeratorOID($roles);

		if ( 0 == $moderator_oid ) {
			$this->returnErrorStatus($cp, 'moderator not found');
			return false;
		}

		$user_role = $this->getUserRole( $users, $user_id, $roles );

		if ( 0 == $moderator_oid ) {
			$this->returnErrorStatus($cp, 'undefined user role');
			return false;
		}

		if ( $this->aa->acl_data['user']['user_id'] == $user_id
		&& $moderator_oid == $user_role && $moderator_oid != $role_oid ) {
			$this->returnErrorStatus($cp, 'can`t self downgrade rights');
			return false;
		}

		$this->ctx->db->begin();

		$model = $this->ctx->mm->getModel("User", "m");
		$model->setRoleByOid($community_oid, $user_id, $role_oid);

		$this->ctx->db->end();

		$status = &$cp->add_node('status');
		$data = &$cp->add_node('data');
		$status->set_data(0);
		$data->set_data($role_oid);
		$this->shutdown();
		return true;
	}

	public function ajax_doExorcizeUser ( $user_id )
	{
		$cp = &$this->rh->ctx->cp;

		$operations = $this->aa->getAvailableOperations();
		if ( !$this->aa->is_granted( array( 'community_edit') ) ) {
			$status = &$cp->add_node('status');
			$status->set_data(-1);
			$data = &$cp->add_node('data');
			$data->set_data('access denied');
			$this->shutdown();
			return false;
		}

		$users = $this->getCommunityUsers();
		$roles = $this->getRoles();
		$moderator_oid = $this->getModeratorOID($roles);

		if ( $moderator_oid == $this->aa->acl_data['role']['oid'] ) {
			$moderatorsCount = $this->getModeratorsCount($users, $moderator_oid);
			if ( $moderatorsCount < 2 ) {
				$model = $this->ctx->mm->getModel("User", "m");
				$community_oid = $this->aa->acl_data['comity_oid'];
				foreach ( $users as $user ) {
					$model->setRoleByOid($community_oid, $user['oid'], $moderator_oid);
				}
			}
		}

		$community_oid = $this->aa->acl_data['comity_oid'];

		if ( 1 == count($users) ) {
			$model = $this->ctx->mm->getModel("Community", "m");
			$config = $model->getConfig($community_oid);

			if ('moderated' == $config['join_mode']) {
				$config['join_mode'] = 'free';
				$model->saveConfig($community_oid, $config);
			}
		}

		$community = $this->ctx->store->getObject($community_oid);
		$user = $this->ctx->store->getObject($user_id);

		$user_msg = $this->aa->template_data;
		$user_msg['user'] = $user->data['fullname'];
		$user_msg['to'] = $user->data['email'];
		$user_msg['community'] = $community->data;

		$this->rh->UseClass("Model_MailOutbox");
		$outbox = new Model_MailOutbox( $this->rh, $this->aa );
		$outbox->template = 'email/delete_member_from_community.html';
		$outbox->delete_after_send = true;

		$outbox->post($user_msg);

		$outbox->list->select()->each(array($outbox, 'send'), $outbox->list);

		$this->ctx->db->begin();
		$user = $this->leaveCommunity($community_oid, $user_id);
		$this->ctx->db->end();
		if ($user) {
			$status = &$cp->add_node('status');
			$data = &$cp->add_node('data');
			if ($user->id == $this->acl_data['user_id']) { // change self
				$status->set_data(1);
				// make url to self
				$this->rh->UseClass('RL_URLGenerator');
				$ug = new RL_URLGenerator($this->rh->router->getRule('community_show_users'));
				$ug->setRouter($this->rh->router);
				$ug->setParams($this->params);
				//$ug->setGet($this->rh->GET);
				$url = $ug->generateUrl();
				//$url = $this->getUrl();
				$data->set_data($url);
			} else {  // change other user
				$status->set_data(0);
				$data->set_data($role);
			}
			$this->shutdown();
			return true;
		} else {
			$status = &$cp->add_node('status');
			$status->set_data(-1);
			$data = &$cp->add_node('data');
			$data->set_data('not found');
			$this->shutdown();
			return false;
		}
	}

	public function init()
	{
		parent::init();
		$this->rh->UseClass('RL_CyrDate');
	}

	public function process ()
	{
	} // end of function execute

}
